//
//  MTInviteController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/9.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import RxSwift
import RxCocoa
import Moya
import Result
import JXSegmentedView

class MTInviteController: BaseViewController {

    /// MineApi
    private lazy var provider: MTProvider<MineApi> = {
        let provider = MTProvider<MineApi>(plugins: [MTLoadingDataPlugin.init(viewController: self)])
        return provider
    }()
    
    private let disposeBag = DisposeBag()
    private var result: [MTInviteListModel] = []
    private var currentPage: Int = 1
    private let pageSize: Int = 20
//    var naviDataSource = JXSegmentedTitleDataSource()
//    lazy var naviSegmentedView = JXSegmentedView()
//    lazy var listContainer = JXSegmentedListContainerView(dataSource: self, type: .scrollView)
//
//    var lists: [JXSegmentedListContainerViewListDelegate?] = []
    
    
    var model: MineInfoModel?
    
    lazy var tableView: UITableView = {
        let table = UITableView(frame: .zero, style: .plain)
        table.delegate = self
        table.dataSource = self
        
        table.register(InvitedListCell.self, forCellReuseIdentifier: InvitedListCell.reuseIdentity())
        table.separatorStyle = .none
        table.tableFooterView = UIView()
        table.emptySetView = ViewFactory.emptySetView { [weak self] in

            guard let weakSelf = self else { return }

            weakSelf.loadFirst()

        }
        table.mj_header = ViewFactory.normalHeader(target: self, selector: #selector(loadFirst))
        table.mj_footer = ViewFactory.normalFooter(target: self, selector: #selector(loadMore))
        return table
    }()
    
    lazy var headerBack: UIImageView = {
        let view = UIImageView()
        view.image = UIImage(named: "head-bg")
        return view
    }()
    
    lazy var titleLab: UILabel = {
        let lab = UILabel()
        lab.text = "累计获得钻石奖励"
        lab.font = PingFangSCMediumFont(12)
        lab.textColor = UIColor(hex:0x9b9b9b)
        lab.textAlignment = .center
        return lab
    }()
    
    lazy var icon: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(named: "dimond")
        return imageView
    }()
    
    lazy var amountLabel: UILabel = {
        let l = UILabel()
        l.textColor = .white
        l.font = PingFangSCSemiboldFont(20)
        l.text = "0"
        l.textAlignment = .right
        return l
    }()
    
    lazy var invitedBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("已邀请", for: .normal)
        btn.setTitleColor(UIColor(hex:0xffc000), for: .normal)
        btn.setTitleColor(.white, for: .selected)
        btn.titleLabel?.font = PingFangSCSemiboldFont(14)
        btn.addTarget(self, action: #selector(inviteController(didClickInviteButton:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var invitedUnderLine: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex:0xffc000)
        view.layer.cornerRadius = 2
        return view
    }()
    
    lazy var unloginBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("未登录", for: .normal)
        btn.setTitleColor(UIColor(hex:0xffc000), for: .normal)
        btn.setTitleColor(.white, for: .selected)
        btn.titleLabel?.font = PingFangSCSemiboldFont(14)
        btn.addTarget(self, action: #selector(inviteController(didClickUnloginButton:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var unloginUnderLine: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex:0xffc000)
        view.layer.cornerRadius = 2
        return view
    }()
    
    lazy var footerBack: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(hex:0x1d1a1a)
        return view
    }()
    
    lazy var footerInviteBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("邀请好友", for: .normal)
        btn.setTitleColor(UIColor(hex:0x1d1a1a), for: .normal)
        btn.backgroundColor = UIColor(hex:0xffc000)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.layer.cornerRadius = 20
        btn.addTarget(self, action: #selector(inviteController(didClickInviteButton:)), for: .touchUpInside)
        return btn
    }()
    
    override func refreshView() {
        loadFirst()
    }
    
    private func loadData(loadMore: Bool) {
        provider.rx.requestResult(.inviteList(currentPage)).subscribe(onNext: { [weak self] (result:Result<MTInviteModel, AnyError> , isCache:Bool) in
            guard let weakSelf = self else { return }
            switch result {
            case .success(let model):
                if model.code == 200 {
                
                    weakSelf.tableView.mj_footer?.endRefreshing()
                    weakSelf.tableView.mj_header?.endRefreshing()
                    if weakSelf.currentPage == 1 {
                        weakSelf.tableView.mj_footer?.state = .idle
                    }
                    
                    if let r = model.result {
                        if (model.page?.pages == weakSelf.currentPage) {
                            weakSelf.tableView.mj_footer?.endRefreshingWithNoMoreData()
                        }
                        if loadMore == true {
                            weakSelf.result = weakSelf.result + r
                        } else {
                            weakSelf.result = r
                        }
                    }
                    
                    DispatchQueue.main.async {
                        weakSelf.tableView.reloadData()
                    }
                }
                break
            case .failure( _):
                
                break
            }
            
        }).disposed(by: globalDisposedBag)
    }
    
    @objc private func hiddenHF(isHidden: Bool) {
        self.tableView.mj_header?.isHidden = isHidden
        self.tableView.mj_footer?.isHidden = isHidden
    }
    
    @objc private func loadFirst() {
        self.currentPage = 1
        
        loadData(loadMore: false)
    }
    
    @objc private func loadMore() {
        
        self.currentPage = self.currentPage + 1
        
        loadData(loadMore: true)
        
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hex: 0xf6f6f6)
        title = "邀请好友"
        let button = UIButton(frame: CGRect(x: 0, y: 0, width: 56, height: 20))
        button.setTitle("奖励规则", for: .normal)
        button.setTitleColor(UIColor(hex:0x1d1a1a), for: .normal)
        button.titleLabel?.font = PingFangSCMediumFont(14)
        button.addTarget(self, action: #selector(inviteController(didClickruleButton:)), for: .touchUpInside)
        let rightBarButton = UIBarButtonItem(customView: button)
        self.navigationItem.rightBarButtonItem = rightBarButton
        
        let header = headerView()
        view.addSubview(header)
        view.addSubview(tableView)
        view.addSubview(footerBack)
        footerBack.addSubview(footerInviteBtn)

        header.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(NavigationBarHeight+StatusBarHeight)
            make.height.equalTo(90)
        }
        
        tableView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 90+NavigationBarHeight+StatusBarHeight, left: 0, bottom: 50, right: 0))
        }
        
        footerBack.snp.makeConstraints { (make) in
            make.width.equalTo(ScreenWidth)
            make.height.equalTo(50+ScreenBottomExtraOffset)
            make.bottom.equalTo(view)
        }
        
        footerInviteBtn.snp.makeConstraints { (make) in
            make.centerY.equalTo(footerBack)
            make.height.equalTo(40)
            make.left.equalTo(footerBack).offset(55)
            make.right.equalTo(footerBack).offset(-55)
        }
        
        loadFirst()
    }
}

extension MTInviteController {
    private func headerView() -> UIView {
        headerBack.addSubview(titleLab)
        headerBack.addSubview(icon)
        headerBack.addSubview(amountLabel)

        
        titleLab.snp.makeConstraints { (make) in
            make.centerX.equalTo(headerBack)
            make.top.equalTo(20)
        }
        
        amountLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(titleLab).offset(-8)
            make.top.equalTo(titleLab.snp.bottom).offset(3)
        }
        
        icon.snp.makeConstraints { (make) in
            make.left.equalTo(amountLabel.snp.right).offset(4)
            make.centerY.equalTo(amountLabel)
            make.width.height.equalTo(24)
        }
        
        return headerBack
    }
}

extension MTInviteController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTInviteController {
    
    private func inviteController(didClickruleButton sender: UIButton) {
        let xibView = InviteRuleAlertView.init(frame: CGRect(x:0, y:0, width:ScreenWidth, height:ScreenHeight))
        UIApplication.mt_keyWindow?.addSubview(xibView)
    }
    
    private func inviteController(didClickInviteButton sender: UIButton) {
        let xibView = InviteShareAlertView.init(frame: CGRect(x:0, y:0, width:ScreenWidth, height:ScreenHeight))
//        xibView.model = model
        UIApplication.mt_keyWindow?.addSubview(xibView)
    }

    private func inviteController(didClickUnloginButton sender: UIButton) {
        
    }
}

extension MTInviteController: UITableViewDataSource, UITableViewDelegate {
    
    //MARK: UITableViewDataSource
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.result.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: InvitedListCell.reuseIdentity(), for: indexPath) as! InvitedListCell
        cell.delegate = self
        if self.result.count > indexPath.row {
            cell.model = self.result[indexPath.row]
        }
        return cell
    }
    
    //MARK: UITableViewDelegate
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 129
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNonzeroMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
}

extension MTInviteController: InvitedListCellDelegate {
    func invitedListCellDidClickChatButton(_ cell: InvitedListCell, isPlay: Bool) {
//        let xibView = InviteShareAlertView.init(frame: CGRect(x:0, y:0, width:ScreenWidth, height:ScreenHeight))
//        xibView.model = self.result[0]
//        self.view.addSubview(xibView)
//        navigationController?.pushViewController(MyQRCodeViewController(), animated: true)
        guard let indexPath = self.tableView.indexPath(for: cell) else { return }
        let model = self.result[indexPath.item]
        guard let un = model.userName else { return }
        self.presentGiftView(isFriend: false, imUserName: un, didClickRechargeCallBack: { [weak self] in
            guard let weakself = self else { return }
            if UserDefaults.AppValidate.isValidate.storedBool == false {
                let c = MTPaymentViewController()
                weakself.navigationController?.pushViewController(c, animated: true)
            } else {
                let c = MTInAppPurchasesViewController()
                weakself.navigationController?.pushViewController(c, animated: true)
            }
            }, selectedGiftCallBack: { [weak self] (model, count) in
                
        }, didClickSayHiCallBack: { [weak self] (model, count) in
            guard let weakself = self else { return }
            let c = MTAddFriendViewController(giftCount: count, targetUserName: un, giftModel: model)
            weakself.navigationController?.pushViewController(c, animated: true)
        }) {
            
        }
    }
}


